package com.jz.community.moduleshoppingguide.home.ui.adapter;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import com.jz.community.moduleshoppingguide.home.ui.fragment.PreferentialFragment;

public class PreferentialAdapter extends FragmentPagerAdapter {


    private FragmentManager fm;
    private String[] nameList = {"全部", "可用券", "折扣", "预售", "免邮"};

    public PreferentialAdapter(FragmentManager fm) {
        super(fm);
        this.fm = fm;
    }

    @Override
    public PreferentialFragment getItem(int position) {
        return PreferentialFragment.newInstance(position + "");
    }

    @Override
    public int getCount() {
        return nameList.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return nameList[position];
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        //拿到缓存的fragment，如果没有缓存的，就新建一个，新建发生在fragment的第一次初始化时
        PreferentialFragment f = (PreferentialFragment) super.instantiateItem(container, position);
        String fragmentTag = f.getTag();
        if (f != getItem(position)) {
            //如果是新建的fragment，f 就和getItem(position)是同一个fragment，否则进入下面
            FragmentTransaction ft = fm.beginTransaction();
            //移除旧的fragment
            ft.remove(f);
            //换成新的fragment
            f = getItem(position);
            //添加新fragment时必须用前面获得的tag
            ft.add(container.getId(), f, fragmentTag);
            ft.attach(f);
            ft.commitAllowingStateLoss();
        }
        return f;
    }
}
